
//客服接口

package miniapp

import (
    "fmt"
	"errors"
	"wxsdk/miniapp/core"
	"github.com/astaxie/beego"
)
var (
	customerURL = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=%s" 
)

// 发送文本消息
func  SendTextMessage(authorizerAccessToken, touser, content string)(string,error){
	serverUrl := fmt.Sprintf(customerURL, authorizerAccessToken)
	client := core.GetPostJSONClient()
	text := NewText(touser, content)
	var rsp core.ErrorResponse
	tbdata, err := client.Excute("POST", serverUrl, text, &rsp)
    if err != nil {
		beego.Critical(err.Error())
		return "", err
	}
	if rsp.ErrCode != 0 {
		beego.Critical("error:", string(tbdata))
		return "",errors.New(string(tbdata)) 
	}
	return string(tbdata), nil
}

// 发送图片消息
func  SendImageMessage(authorizerAccessToken, touser, mediaId string)(string,error){
	serverUrl := fmt.Sprintf(customerURL, authorizerAccessToken)
	client := core.GetPostJSONClient()
	image := NewImage(touser, mediaId)
	var rsp core.ErrorResponse
	tbdata, err := client.Excute("POST", serverUrl, image, &rsp)
    if err != nil {
		beego.Critical(err.Error())
		return "", err
	}
	if rsp.ErrCode != 0 {
		beego.Critical("error:", string(tbdata))
		return "",errors.New(string(tbdata)) 
	}
	return string(tbdata), nil
}

// 发送图文消息
func  SendLinkMessage(authorizerAccessToken,toUser,title,description,url,thumbUrl string)(string,error){
	serverUrl := fmt.Sprintf(customerURL, authorizerAccessToken)
	client := core.GetPostJSONClient()
	link := NewLink(toUser,title,description,url,thumbUrl)
	var rsp core.ErrorResponse
	tbdata, err := client.Excute("POST", serverUrl, link, &rsp)
    if err != nil {
		beego.Critical(err.Error())
		return "", err
	}
	if rsp.ErrCode != 0 {
		beego.Critical("error:", string(tbdata))
		return "",errors.New(string(tbdata)) 
	}
	return string(tbdata), nil
}

// 发送小程序卡片消息
func  SendMiniProgramPageMessage(authorizerAccessToken,toUser,title,pagePath,thumbMediaId string)(string,error){
	serverUrl := fmt.Sprintf(customerURL, authorizerAccessToken)
	client := core.GetPostJSONClient()
	miniProgramPage := NewMiniProgramPage(toUser,title,pagePath,thumbMediaId)
	var rsp core.ErrorResponse
	tbdata, err := client.Excute("POST", serverUrl, miniProgramPage, &rsp)
    if err != nil {
		beego.Critical(err.Error())
		return "", err
	}
	if rsp.ErrCode != 0 {
		beego.Critical("error:", string(tbdata))
		return "",errors.New(string(tbdata)) 
	}
	return string(tbdata), nil
}
